//
//  HWRequestLogManage
//
//  Created by 李含文 on 2021/4/28.
//  Copyright © 2021 MINISO. All rights reserved.
//

#import "HWRequestLogManage.h"
#import "HWLogViewModel.h"
#import "HWLogSuspendButton.h"
#import "HWLogViewController.h"
#import "HWHttpProtocol.h"
#import "HWLogSuspendButton.h"

@interface HWRequestLogManage()

/// <#name#>
@property (nonatomic, assign) BOOL isOpen;
/// <#name#>
@property (nonatomic, strong) HWLogSuspendButton *button;

@property (strong, nonatomic) UILabel *displayLabel;
@property (strong, nonatomic) CADisplayLink *link;
@property (assign, nonatomic) NSInteger count;
@property (assign, nonatomic) NSTimeInterval lastTime;
@end

@implementation HWRequestLogManage

+ (HWRequestLogManage *)shared {
    static HWRequestLogManage * manage = nil;
    static dispatch_once_t once;
    dispatch_once(&once,^{
        manage = [[self alloc] init];
    });
    return manage;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self addObserver];
        [self initCADisplayLink];
    }
    return self;
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataUpdate) name:k_HWLogViewModel_DataUpdate object:nil];
}

- (void)dataUpdate {
    if (!self.isOpen) return;
    hwlog_dispatch_main_queue(^{
        [self.button.superview bringSubviewToFront:self.button];
    });
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_link invalidate];
    _link = nil;
}


- (void)openWithWindow:(UIWindow *)window {
    _isOpen = YES;
    _window = window;
    [self addSuspendButton];
    [NSURLProtocol registerClass:[HWHttpProtocol class]];
}

- (void)disable {
    _isOpen = NO;
    [NSURLProtocol unregisterClass:[HWHttpProtocol class]];
    [self.button removeFromSuperview];
}


- (void)addSuspendButton {
    UIWindow *window = _window;
    if (!window) return;
    [window addSubview:self.button];
}
- (HWLogSuspendButton *)button {
    if (!_button) {
        HWLogSuspendButton *button = [HWLogSuspendButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(UIScreen.mainScreen.bounds.size.width-50, UIScreen.mainScreen.bounds.size.height-200, 50, 50);
        button.cornerRadius = 25;
        button.MoveEnable = YES;
        button.backgroundColor = [UIColor.grayColor colorWithAlphaComponent:0.8];
        [button setTitle:@"请求日志" forState:(UIControlStateNormal)];
        button.contentEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);
        button.titleLabel.font = [UIFont systemFontOfSize:10];
        button.titleLabel.numberOfLines = 0;
        [button setTitleColor:UIColor.whiteColor forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        _button = button;
        self.displayLabel.frame = CGRectMake(0, 10, 50, 10);
        [button addSubview:self.displayLabel];
    }
    return _button;
}

- (void)getVisibleViewController:(void(^)(UIViewController *vc))action {
    hwlog_dispatch_main_queue(^{
        UIViewController *currentViewController = self->_window.rootViewController;
        while (1) {
            if (currentViewController.presentedViewController)
                currentViewController = currentViewController.presentedViewController;
            else {
                if ([currentViewController isKindOfClass:[UINavigationController class]])
                    currentViewController = ((UINavigationController *)currentViewController).visibleViewController;
                else if ([currentViewController isKindOfClass:[UITabBarController class]])
                    currentViewController = ((UITabBarController* )currentViewController).selectedViewController;
                else
                    break;
            }
        }
        if (action) action(currentViewController);
    });
}
- (void)btnClick {
    HWLogViewController *vc = [HWLogViewController new];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self getVisibleViewController:^(UIViewController * _Nonnull vc) {
        [vc presentViewController:nav animated:YES completion:nil];
    }];
}


- (void)initCADisplayLink {
    self.link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)tick:(CADisplayLink *)link {
    if (self.lastTime == 0) {           //对LastTime进行初始化
        self.lastTime = link.timestamp;
        return;
    }

    _count++;
    NSTimeInterval delta = link.timestamp - self.lastTime; //计算本次刷新和上次更新FPS的时间间隔
    if (delta < 1) return; //大于等于1秒时，来计算FPS
    _lastTime = link.timestamp;
    float fps = _count / delta; // 次数 除以 时间 = FPS （次/秒）
    _count = 0;
    [self updateDisplayLabelText: fps];
}

- (void)updateDisplayLabelText: (float) fps {
    CGFloat progress = fps / 60.0;
    UIColor *color = [UIColor colorWithHue:0.27 * (progress - 0.2) saturation:1 brightness:0.9 alpha:1];
    
    NSMutableAttributedString *attText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d FPS",(int)round(fps)]];
    //设置颜色
    [attText addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, attText.length - 3)];
    [attText addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(attText.length - 3, 3)];
    
    //设置字体
    [attText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(0, attText.length - 3)];
    [attText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(attText.length - 3, 3)];
    self.displayLabel.attributedText = attText;
}

- (UILabel *)displayLabel {
    if (!_displayLabel) {
        _displayLabel = [UILabel new];
        _displayLabel.font = [UIFont systemFontOfSize:10];
        _displayLabel.textColor = UIColor.whiteColor;
        _displayLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _displayLabel;
}
@end
